/*
 * CodeUtil.java
 * CodeUtil.java
 *
 * Created on __DATE__, __TIME__
 */

package com.ndood.code.ui;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import com.ndood.code.template.Code;
import com.ndood.code.xml.XmlUtil;

/**
 * 贝帛吱付代码生成器 V2.4
 *
 * @author ndood
 *
 */
public class CodeUtil extends javax.swing.JFrame {
	private static final long serialVersionUID = 7277156064646021666L;
	/** Creates new form CodeUtil */
	public CodeUtil() {
		initComponents();
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	// GEN-BEGIN:initComponents
	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {

		labelTemplate = new JLabel();
		labelDocPath = new JLabel();
		jSeparator1 = new javax.swing.JSeparator();
		textDocPath = new javax.swing.JTextField();
		labelCodePath = new JLabel();
		textCodePath = new javax.swing.JTextField();
		jSeparator2 = new javax.swing.JSeparator();
		labelProjectName = new JLabel();
		textProjectName = new javax.swing.JTextField();
		labelProjectComment = new JLabel();
		textPackage = new javax.swing.JTextField();
		labelPackage = new JLabel();
		textProjectComment = new javax.swing.JTextField();
		labelAuthor = new JLabel();
		textAthor = new javax.swing.JTextField();
		btnGenerateCode = new javax.swing.JButton();
		btnClose = new javax.swing.JButton();
		btnSelectDocPath = new javax.swing.JButton();
		btnSelectCodePath = new javax.swing.JButton();
		labelDb = new JLabel();
		textDb = new javax.swing.JTextField();
		labelUsername = new JLabel();
		textUsername = new javax.swing.JTextField();
		labelPassword = new JLabel();
		textPassword = new javax.swing.JTextField();
		selectTemplate = new javax.swing.JComboBox<String>();

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
		setTitle("贝帛吱付代码生成器 1.0");
		addWindowListener(new java.awt.event.WindowAdapter() {
			public void windowActivated(java.awt.event.WindowEvent evt) {
				formWindowActivated(evt);
			}

			public void windowOpened(java.awt.event.WindowEvent evt) {
				formWindowOpened(evt);
			}

			public void windowClosing(java.awt.event.WindowEvent evt) {
				formWindowClosing(evt);
			}
		});

		labelTemplate.setText("模板");

		labelDocPath.setText("结构文档路径");

		labelCodePath.setText("代码生成路径");

		labelProjectName.setText("项目名（英文）");

		labelProjectComment.setText("项目中文名称");

		labelPackage.setText("包名");

		labelAuthor.setText("作者");

		btnGenerateCode.setText("生成代码");
		btnGenerateCode.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnGenerateCodeActionPerformed(evt);
			}
		});

		btnClose.setText("关闭");
		btnClose.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnCloseActionPerformed(evt);
			}
		});

		btnSelectDocPath.setText("选择");
		btnSelectDocPath.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnSelectDocPathActionPerformed(evt);
			}
		});

		btnSelectCodePath.setText("选择");
		btnSelectCodePath.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnSelectCodePathActionPerformed(evt);
			}
		});

		labelDb.setText("labelDb");

		labelUsername.setText("用户名");

		labelPassword.setText("密码");

		selectTemplate.setModel(new javax.swing.DefaultComboBoxModel<String>(new String[] { "--请选择模板--" }));

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addComponent(jSeparator2, javax.swing.GroupLayout.DEFAULT_SIZE, 543, Short.MAX_VALUE)
				.addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING,
						javax.swing.GroupLayout.DEFAULT_SIZE, 543, Short.MAX_VALUE)
				.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addGroup(layout
						.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(layout.createSequentialGroup().addGap(26, 26, 26)
								.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
										.addComponent(labelDocPath)
										.addGroup(layout.createSequentialGroup()
												.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
												.addComponent(labelCodePath))))
						.addGroup(layout.createSequentialGroup().addGap(25, 25, 25)
								.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
										.addComponent(labelProjectName).addComponent(labelPackage).addComponent(labelProjectComment)
										.addComponent(labelAuthor).addComponent(labelDb).addComponent(labelUsername))))
						.addGap(0, 0, 0)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
								.addGroup(layout.createSequentialGroup()
										.addComponent(textUsername, javax.swing.GroupLayout.PREFERRED_SIZE, 104,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addGap(18, 18, 18).addComponent(labelPassword).addGap(36, 36, 36)
										.addComponent(textPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 118,
												Short.MAX_VALUE))
								.addComponent(textDb, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
								.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
										layout.createSequentialGroup().addComponent(btnGenerateCode)
												.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
														140, Short.MAX_VALUE)
												.addComponent(btnClose, javax.swing.GroupLayout.PREFERRED_SIZE, 79,
														javax.swing.GroupLayout.PREFERRED_SIZE))
								.addComponent(textDocPath, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
								.addComponent(textCodePath, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
								.addComponent(textProjectName, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
								.addComponent(textPackage, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
								.addComponent(textProjectComment, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
								.addComponent(textAthor, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE))
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
								.addComponent(btnSelectCodePath, javax.swing.GroupLayout.Alignment.LEADING, 0, 0,
										Short.MAX_VALUE)
								.addComponent(btnSelectDocPath, javax.swing.GroupLayout.Alignment.LEADING,
										javax.swing.GroupLayout.DEFAULT_SIZE, 73, Short.MAX_VALUE))
						.addGap(54, 54, 54))
				.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addGap(27, 27, 27)
						.addComponent(labelTemplate).addGap(57, 57, 57).addComponent(selectTemplate,
								javax.swing.GroupLayout.PREFERRED_SIZE, 299, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addGap(136, 136, 136)));
		layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(layout.createSequentialGroup().addGap(96, 96, 96)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
								.addComponent(selectTemplate, javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
								.addComponent(labelTemplate))
						.addGap(18, 18, 18)
						.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10,
								javax.swing.GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
								.addComponent(labelDocPath).addComponent(textDocPath).addComponent(btnSelectDocPath))
						.addGap(15, 15, 15)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
								.addComponent(labelCodePath).addComponent(textCodePath).addComponent(btnSelectCodePath))
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
						.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10,
								javax.swing.GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
								.addComponent(labelProjectName).addComponent(textProjectName))
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
								.addComponent(labelPackage).addComponent(textPackage))
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
								.addComponent(labelProjectComment).addComponent(textProjectComment))
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
								.addComponent(textAthor).addComponent(labelAuthor))
						.addGap(18, 18, 18)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
								.addComponent(labelDb).addComponent(textDb))
						.addGap(18, 18, 18)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
								.addComponent(labelUsername)
								.addComponent(textUsername, javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
								.addComponent(labelPassword).addComponent(textPassword,
										javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
										javax.swing.GroupLayout.PREFERRED_SIZE))
						.addGap(26, 26, 26)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
								.addComponent(btnClose).addComponent(btnGenerateCode))
						.addGap(24, 24, 24)));

		pack();
	}// </editor-fold>
		// GEN-END:initComponents

	/**
	 * 窗口关闭事件
	 */
	private void formWindowClosing(java.awt.event.WindowEvent evt) {
		dispose();
		System.exit(0);
	}

	/**
	 * 窗口打开事件
	 */
	private void formWindowOpened(java.awt.event.WindowEvent evt) {

		setLocationRelativeTo(null);

		// Step1: 获取所有模板文件
		File directory = new File(new File("").getAbsolutePath() + "\\src\\main\\resources\\templates");// 设定为当前文件夹
		File[] listFiles = directory.listFiles();
		if (listFiles != null) {
			for (File f : listFiles) {
				if (f.isDirectory()) {
					this.selectTemplate.addItem(f.getName());
				}
			}
		}
		
		// Step2: 设置数据库文档路径
		this.textDocPath.setText(new File("").getAbsolutePath() + "\\src\\main\\resources\\db");

		// Step3: 设置基本参数
		Map<String, String> publicMap = XmlUtil.read("publicMap.xml");
		if (publicMap != null && publicMap.size() > 0) {
			this.textProjectName.setText(publicMap.get("project"));
			this.textPackage.setText(publicMap.get("package"));
			this.textProjectComment.setText(publicMap.get("projectComment"));
			this.textAthor.setText(publicMap.get("author"));
			// this.textDb.setText(publicMap.get("db"));
			// this.textUsername.setText(publicMap.get("dbuser"));
			// this.textPassword.setText(publicMap.get("dbpassword"));
		}
	}

	private void formWindowActivated(java.awt.event.WindowEvent evt) {

	}

	/**
	 * 窗口关闭事件
	 */
	private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {
		// this.dispose();
		System.exit(0);
	}

	public void setDbInfo(String dbName, String dbuser, String dbpassword) {
		this.textDb.setText(dbName);
		this.textUsername.setText(dbuser);
		this.textPassword.setText(dbpassword);
	}

	/**
	 * 点击生成代码按钮事件
	 */
	private void btnGenerateCodeActionPerformed(java.awt.event.ActionEvent evt) {
		btnGenerateCode.setEnabled(false);
		btnGenerateCode.setText("代码生成中...");
		final Thread t = new Thread(new Runnable() {
			public void run() {
				try {
					
					// Step1: 设置选择模板后的根路径
					String basePath = new File("").getAbsolutePath() + "\\src\\main\\resources\\templates\\" + selectTemplate.getSelectedItem();// 设定为当前文件夹

					Map<String, String> pathMap = new HashMap<String, String>();
					pathMap.put("templetPath", basePath); // 模板根路径
					pathMap.put("projectTempletPath", basePath + "\\工程模板"); // 工程模板路径 
					pathMap.put("tablleTempletPath", basePath + "\\表级模板"); // 表级模板路径
					pathMap.put("columnTempletPath", basePath + "\\列级模板"); // 列级模板路径
					pathMap.put("xmlPath", textDocPath.getText()); // 数据库xml文档路径
					pathMap.put("codePath", textCodePath.getText()); // 代码输出路径

					// Step2: 设置全局Map
					Map<String, String> publicMap = new HashMap<String, String>();
					publicMap.put("project", textProjectName.getText());
					publicMap.put("package", textPackage.getText());
					publicMap.put("projectComment", textProjectComment.getText());
					publicMap.put("author", textAthor.getText());
					publicMap.put("db", textDb.getText());
					publicMap.put("dbuser", textUsername.getText());
					publicMap.put("dbpassword", textPassword.getText());
					String s = textPackage.getText().replace(".", ",");
					String[] paths = s.split(",");
					for (int i = 0; i < paths.length; i++) {
						// path_1:com, path_2:ndood, path_3:agent package的数量必须和模板保持一致
						publicMap.put("path_" + String.valueOf(i + 1), paths[i]); 
					}
					publicMap.put("path_all", s.replace(",", "/"));  // com/ndood/agent
					
					// Step3: 缓存提交的变量到xml文件
					XmlUtil.write(publicMap, "publicMap.xml");

					// Step4: 生成代码
					Code.create(pathMap, publicMap);
					JOptionPane.showMessageDialog(null, "代码生成成功", "提示", JOptionPane.DEFAULT_OPTION);

				} catch (Exception e) {
					e.printStackTrace();
					JOptionPane.showMessageDialog(null, "发生错误", "错误详情请查看error.log", JOptionPane.INFORMATION_MESSAGE);

				}
				
				btnGenerateCode.setEnabled(true);
				btnGenerateCode.setText("生成代码");

			}
		});
		t.start();

	}

	private void btnSelectCodePathActionPerformed(java.awt.event.ActionEvent evt) {
		this.textCodePath.setText(selectPath("选择代码生成路径"));
	}

	private void btnSelectDocPathActionPerformed(java.awt.event.ActionEvent evt) {
		this.textDocPath.setText(selectPath("选择结构文档路径"));
	}

	@SuppressWarnings("unused")
	private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
		// this.jTextField2.setText(selectPath("选择表级模板路径"));
	}

	/**
	 * 选择路径
	 * 
	 * @param title
	 * @return
	 */
	private String selectPath(String title) {
		JFileChooser jfc = new JFileChooser();
		jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		jfc.showDialog(new JLabel(), title);
		File file = jfc.getSelectedFile();
		if (file == null) {
			return null;
		}
		return file.getPath();
	}

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new CodeUtil().setVisible(true);
			}
		});
	}

	// GEN-BEGIN:variables
	// Variables declaration - do not modify
	private javax.swing.JButton btnGenerateCode;
	private javax.swing.JButton btnClose;
	private javax.swing.JButton btnSelectDocPath;
	private javax.swing.JButton btnSelectCodePath;
	private javax.swing.JComboBox<String> selectTemplate;
	private JLabel labelTemplate;
	private JLabel labelUsername;
	private JLabel labelPassword;
	private JLabel labelDocPath;
	private JLabel labelCodePath;
	private JLabel labelProjectName;
	private JLabel labelProjectComment;
	private JLabel labelPackage;
	private JLabel labelAuthor;
	private javax.swing.JSeparator jSeparator1;
	private javax.swing.JSeparator jSeparator2;
	private javax.swing.JTextField textDb;
	private javax.swing.JTextField textUsername;
	private javax.swing.JTextField textPassword;
	private javax.swing.JTextField textDocPath;
	private javax.swing.JTextField textCodePath;
	private javax.swing.JTextField textProjectName;
	private javax.swing.JTextField textPackage;
	private javax.swing.JTextField textProjectComment;
	private javax.swing.JTextField textAthor;
	private JLabel labelDb;
	// End of variables declaration//GEN-END:variables

}